﻿using System.Diagnostics;
using System.Threading.Tasks;
using Wedonek.Demo.RemoteModel.DBOrder;
using Wedonek.Demo.RemoteModel.DBOrderLog;
using Wedonek.Gateway.Modular.Interface;
using Wedonek.Gateway.Modular.Model;
using WeDonekRpc.Client.Interface;
using WeDonekRpc.Client.Tran;
using WeDonekRpc.Helper;

namespace Wedonek.Gateway.Modular.Service
{
    internal class DBOrderService : IDBOrderService
    {
        public string PressureTest (long userId, int num)
        {
            int errorNum = 0;
            Stopwatch watch = new Stopwatch();
            watch.Start();
            string title = "测试订单!";
            ParallelLoopResult result = Parallel.For(0, num, (i) =>
            {
                try
                {
                    _ = this.AddOrder(new OrderParam
                    {
                        OrderPrice = i,
                        OrderTitle = title
                    }, userId);
                }
                catch
                {
                    _ = System.Threading.Interlocked.Increment(ref errorNum);
                }
            });
            watch.Stop();
            return string.Concat(watch.ElapsedMilliseconds + " _ " + errorNum);
        }
        public long AddOrder (OrderParam add, long userId)
        {
            string orderNo = Tools.GetSerialNo("DE01");
            long id;
            using (IRpcTransaction tran = new RpcTransaction())
            {
                id = new AddDbOrder
                {
                    OrderNo = orderNo,
                    OrderPrice = add.OrderPrice,
                    OrderTitle = add.OrderTitle,
                    UserId = userId
                }.Send();
                long logId = new AddOrderLog
                {
                    OrderId = id,
                    OrderPrice = add.OrderPrice,
                    UserId = userId
                }.Send();
                tran.Complate();//提交事务
            }
            return id;
        }
    }
}
